import re
import xlwt
from openpyxl import Workbook
from numpy import *
import pymysql
import time
# 获取时间
from util_db import DataBaseHandle

ticks = time.time()
# 加载数据库
DbHandle = DataBaseHandle()
# 读取参数文件，将文件根据每行的空格隔开
for i in range(4, 18):
    fp1 = open("C:\\Users\\wddlz\\Desktop\\11\\" + str(i) + ".log")
    str_list = []
    h_id_s = DbHandle.selectDb_2(
        "SELECT id from machine_hardware_information where hardware_ip='10.88.66.36' limit 1 "
    )
    id = h_id_s[0]['id']
    t_id_s = DbHandle.selectDb_2(
        'select task_id from task where h_id = 14  and task_id =41')
    task_id = t_id_s[0]['task_id']
    data1 = []
    data2 = []
    sql1 = "INSERT INTO cpu(h_id, t_id, Average_cpu, Average_usr, Average_nice, Average_sys, Average_iowait, Average_irq, Average_soft, Average_steal, Average_guest, Average_gnice, Average_idle )VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
    sql2 = "INSERT INTO cpu(h_id,t_id,date, all_cpu_num,usr,nice,sys,iowait,irq,soft,steal,guest,guice,idle,AMorPM) VALUES(%s,%s,%s, %s,%s,%s, %s,%s,%s, %s,%s,%s, %s, %s, %s)"
    print(str_list)
    for line in fp1.readlines():
        str_list = line.split()
        if str_list and len(str_list) > 10 and str_list[
                3] != '%usr' and str_list[2] != 'all':
            if str_list[0] == "Average:":  # 当他不是时，则将数据写入
                data1.append(
                    (id, task_id, str_list[1], str_list[2], str_list[3],
                     str_list[4], str_list[5], str_list[6], str_list[7],
                     str_list[8], str_list[9], str_list[10], str_list[11]))
            else:
                data2.append(
                    (id, task_id, str_list[0], str_list[2], str_list[3],
                     str_list[4], str_list[5], str_list[6], str_list[7],
                     str_list[8], str_list[9], str_list[10], str_list[11],
                     str_list[12], str_list[1]))
        if (len(data1) == 40000):
            DbHandle.insertDBmany(sql1, data1)
            data1 = []
        if (len(data2) == 40000):
            DbHandle.insertDBmany(sql2, data2)
            data2 = []

    if len(data1) > 0:
        DbHandle.insertDBmany(sql1, data1)
    if len(data2) > 0:
        DbHandle.insertDBmany(sql2, data2)
    fp1.close()
    print("done")
DbHandle.closeDb()
print("done1")
